package com.ambientrs.script.util;

public class Timer {

    private long startTime;
    private long duration;
    private boolean isPaused;
    private long pauseStartTime;

    /**
     * Starts a new timer with the specified duration.
     *
     * @param millis The duration of the timer.
     */
    public Timer(long millis) {
        isPaused = false;
        startTime = System.currentTimeMillis();
        duration = millis;
    }

    /**
     * Constructs a new stopped timer.
     */
    public Timer() {
        startTime = 0L;
        duration = 0L;
    }

    /**
     * Sets the duration and starts the timer.
     *
     * @param millis The duration of the timer.
     */
    public void setTime(long millis) {
        isPaused = false;
        startTime = System.currentTimeMillis();
        duration = millis;
    }

    /**
     * @return The time, in millis, until the duration has elapsed.
     */
    public long getTimeRemaining() {
        long rem = duration
                - (isPaused ? pauseStartTime : System.currentTimeMillis()
                - startTime);
        return rem > 0 ? rem : 0;
    }

    /**
     * @return True if the duration of the timer has elapsed.
     */
    public boolean hasElapsed() {
        return getTimeRemaining() > 0;
    }

    /**
     * @return True if the timer is not paused and the duration has not elapsed.
     */
    public boolean isRunning() {
        return hasElapsed() && !isPaused;
    }

    /**
     * Pauses the timer.
     */
    public void pause() {
        isPaused = true;
        pauseStartTime = System.currentTimeMillis();
    }

    /**
     * Resumes the timer.
     */
    public void resume() {
        startTime = System.currentTimeMillis() - (pauseStartTime - startTime);
        isPaused = false;
    }

    /**
     * Restarts the timer with the previous duration.
     */
    public void restart() {
        startTime = System.currentTimeMillis();
        isPaused = false;
    }

}
